<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>事件委派案例_table</title>
</head>
<body>
<!--
  th代替td
  caption标题
  thead包裹tr
  tbody包裹tr
  tfoot包裹tr
-->
  <table>
    <tr>
      <th>姓名</th>
      <th>年龄</th>
      <th>性别</th>
      <th>操作</th>
    </tr>
    <tr>
      <td>孙悟空</td>
      <td>20</td>
      <td>男</td>
      <td><a href="javascript:;">删除</a></td>
    </tr>
    <tr>
      <td>白骨精</td>
      <td>18</td>
      <td>女</td>
      <td><a href="javascript:;">删除</a></td>
    </tr>
  </table>
<input type="text" placeholder="请输入姓名">
<br>
<input type="text" placeholder="请输入年龄">
<br>
<input type="text" placeholder="请输入性别">
<br>
<input type="button" id="add" value="添加">
<script>
  var btn = document.getElementById("add");
  
  var inputNodes = document.querySelectorAll("input[type='text']");
  
  var tBodyNode = document.querySelector('table tbody');
  btn.onclick = function () {
    var name = inputNodes[0].value;
    var gender = inputNodes[2].value;
    var age = inputNodes[1].value;
    
    if(name.trim() && gender.trim() && age.trim()){
      var trNode = document.createElement('tr');
      var tdName = document.createElement('td');
      tdName.innerHTML = name;
      trNode.appendChild(tdName);
  
      var tdGender = document.createElement('td');
      tdGender.innerHTML = gender;
      trNode.appendChild(tdGender);
  
      var tdAge = document.createElement('td');
      tdAge.innerHTML = age;
      trNode.appendChild(tdAge);
  
      var tdOperate = document.createElement('td');
      tdOperate.innerHTML = '<a href="javascript:;">删除</a>';
      trNode.appendChild(tdOperate);
  
      tBodyNode.appendChild(trNode);
    }
    
    
    //添加完成情况文本输入
    inputNodes[0].value = '';
    inputNodes[1].value = '';
    inputNodes[2].value = '';
  }
  
  
  //删除 使用事件委派
  tBodyNode.addEventListener('click',function(event){
    //找到点击的那个a的父节点tr
    event = event || window.event;
    var aNode = event.target || event.srcElement;
    var trNode = aNode.parentElement.parentElement;
    tBodyNode.removeChild(trNode);
    
  })
</script>
</body>
</html>